//
//  ApplyForClassLeaveViewController.m
//  AttendenceSys
//
//  Created by ld on 16/1/19.
//  Copyright © 2016年 窦芳俊. All rights reserved.
//

#import "ApplyForClassLeaveViewController.h"


@interface ApplyForClassLeaveViewController ()

@end

@implementation ApplyForClassLeaveViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.strNavTitle = [self getYearMonthDay:[NSDate date]];
    if (_bCallName)
    {
        self.strNavTitle = _sTeaName;
    }
    else
    {
       //[self setRightButtonWithImageName:@"ic_drop" bgImageName:@""];
       [self setRightText:@"选择时间"];
    }
    _weekDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"周一",@"1",
                                                                   @"周二",@"2",
                                                                   @"周三",@"3",
                                                                   @"周四",@"4",
                                                                   @"周五",@"5",
                                                                   @"周六",@"6",
                                                                   @"周日",@"7", nil];
    _appselectArr = [[NSMutableArray alloc] init];
    _sDate = [self.strNavTitle stringByReplacingOccurrencesOfString:@"." withString:@"-"];
    
//    [self setRightCallButtonWithImageName:@"ic_drop" callPressedImageName:@"ic_drop" rightButtonImageName:@"ic_drop" rightPressedImageName:@"ic_drop"];
    
    //[self getStuCourseInfo:_sDate];
    
    if (_bCallName)
    {
        [self initView];//mod 0923 修改请课时假流程 不和courseId相关联 和老师id相关联
        [self getTeaCourseInfo:_appForTeaInfo.userCode];//mod 0923 修改请课时假流程 不和courseId相关联 和老师id相关联
    }
    else
    {
        [self initUI]; // add 0923
    }
}

- (void)initUI
{
    _courseNameContentLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 90, 90, 50)];
    [_courseNameContentLab setText:@"课程名称"];
    [_courseNameContentLab setTextColor:[UIColor blackColor]];
    [_courseNameContentLab setTextAlignment:NSTextAlignmentCenter];
    _courseNameContentLab.font = [UIFont fontWithName:@"Arial" size:18.0];
    [self.view addSubview:_courseNameContentLab];
    
    _courseNameTxtView = [[UITextField alloc] initWithFrame:CGRectMake(_courseNameContentLab.frame.origin.x + _courseNameContentLab.frame.size.width + 10,
                                                                 90,
                                                                 self.view.frame.size.width - (_courseNameContentLab.frame.origin.x + _courseNameContentLab.frame.size.width + 10) - 10,
                                                                 50)];
    _courseNameTxtView.clearButtonMode = UITextFieldViewModeWhileEditing;
    _courseNameTxtView.textColor = [UIColor blackColor];
    _courseNameTxtView.returnKeyType = UIReturnKeyDone;
    [_courseNameTxtView setBackgroundColor:[UIColor clearColor]];
    _courseNameTxtView.placeholder = @"";
    _courseNameTxtView.delegate = self;
    _courseNameTxtView.font = [UIFont systemFontOfSize:18.0f];
    _courseNameTxtView.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:_courseNameTxtView];
    
    
    UIButton* saveBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    saveBtn.frame = CGRectMake(50, 250, [UIScreen mainScreen].bounds.size.width-50*2, 50);
    [saveBtn setTitle:@"下一步" forState:UIControlStateNormal];
    saveBtn.layer.cornerRadius = 4.5;
    [saveBtn addTarget:self action:@selector(nextBtn) forControlEvents:UIControlEventTouchUpInside];
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    saveBtn.backgroundColor = RGB(252, 120, 61);
    saveBtn.enabled = YES;
    [self.view addSubview:saveBtn];
}

- (void)rightButtonPressed:(id)sender
{
    UIView* sourceView = [self topView];
    _backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0,
                                                               0,
                                                               sourceView.frame.size.width,
                                                               sourceView.frame.size.height - 216 - 46)];
    [_backgroundView setBackgroundColor:[UIColor blackColor]];
    _backgroundView.alpha = 0.5;
    [sourceView addSubview:_backgroundView];
    [self initDatePickerView];
}

- (NSString*)getYearMonthDay:(NSDate*)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit
                           | NSMonthCalendarUnit
                           | NSDayCalendarUnit
                           | NSHourCalendarUnit
                           | NSMinuteCalendarUnit
                           | NSSecondCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:date];
    NSString* year = [NSString stringWithFormat:@"%ld", (long)[dateComponent year]];
    NSString* month = [NSString stringWithFormat:@"%ld", (long)[dateComponent month]];
    NSString* day = [NSString stringWithFormat:@"%ld", (long)[dateComponent day]];
    NSString* yearMonthDay = [NSString stringWithFormat:@"%@.%@.%@", year, month, day];
    
    return yearMonthDay;
}

- (void)initDatePickerView
{
    _dateSelctPickerView = [[ASDatePickerView alloc] initWithFrame:CGRectMake(0,
                                                                              self.view.frame.size.height-216-46,
                                                                              [UIScreen mainScreen].bounds.size.width,
                                                                              216 + 46)];
    _dateSelctPickerView.iTag = 0;
    _dateSelctPickerView.editTimeLab.text = @"选择日期";
    _dateSelctPickerView.delegate = self;
    _dateSelctPickerView.datePickerView.datePickerMode = UIDatePickerModeDate;
    NSDate* minDate = [NSDate date];
    //NSDate* maxDate = [[NSDate alloc]initWithString:@"2099-01-01 00:00:00 -0500"];
    
    _dateSelctPickerView.datePickerView.minimumDate = minDate;
    //datePicker.maximumDate = maxDate;
    
    [self.view addSubview:_dateSelctPickerView];
}

//查询课程的http://211.65.216.54/getTeacherCourses.action?userCode=8881
- (void)getTeaCourseInfo:(NSString*)userCode
{
    NSString* refer = @"getTeacherCourses.action?";
    NSString* prefix = kASHttpUrl(refer);
    
    NSString* courseUrl = [NSString stringWithFormat:@"%@userCode=%@", prefix, userCode];
    
    [SVProgressHUD showWithStatus:@"获取老师名下课程..." maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    
    [networkingEngine GET:courseUrl parameters:nil success:^(id responseObject) {
        
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        jsonRsp = [jsonRsp processDictionaryIsNSNull:jsonRsp];
        if (isSuccessRsp(jsonRsp))
        {
            NSArray* data = [jsonRsp objectForKey:kASJsonData];
            _appClassArr = [self parseStuCourseInfo:data];
            _appClassArr = [self sortArray:(NSArray*)_appClassArr];
            [self.tableView reloadData];
            
            if (_appselectArr)
            {
                [_appselectArr removeAllObjects];
            }
            
            [SVProgressHUD dismiss];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
        
    } failure:^(NSError *error) {
        
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}

/*
//获取课程表信息接口 http://121.42.185.124:8080/LawSchool/getUserCourse.action?userCode=xiaohu&termId=1&queryDate=2016-02-17 termId是学期
-(void)getStuCourseInfo:(NSString*)getDate
{
    NSString* refer = @"getUserCourse.action?";
    NSString* prefix = kASHttpUrl(refer);
    
    //ASLoginUserInfo* loginInfo = [ASAppDelegate sharedAppDelegate].userInfo;
    
    NSString* courseUrl = [NSString stringWithFormat:@"%@userCode=%@&termId=%d&queryDate=%@", prefix,AS_APP_UserCode, 1, getDate];
    
    [SVProgressHUD showWithStatus:@"获取课程表..." maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    [networkingEngine GET:courseUrl parameters:nil success:^(id responseObject) {
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        jsonRsp = [jsonRsp processDictionaryIsNSNull:jsonRsp];
        if (isSuccessRsp(jsonRsp))
        {
            NSArray* data = [jsonRsp objectForKey:kASJsonData];
            _appClassArr = [self parseStuCourseInfo:data];
            _appClassArr = [self sortArray:(NSArray*)_appClassArr];
            [self.tableView reloadData];
            if (_appselectArr) {
                [_appselectArr removeAllObjects];
            }
            [SVProgressHUD dismiss];

        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
    } failure:^(NSError *error) {
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}
*/
 
/**
 *	@brief	按 timestamp 倒序排序
 *
 *	@param 	array 	将要被排序的数组
 *
 *	@return	返回倒序排序后的数组
 */
- (NSArray *)sortArray:(NSArray *)array
{
    return [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        
        if ([obj1 isKindOfClass:[ApplyForClassInfo class]])
        {
            ApplyForClassInfo* lhs = (ApplyForClassInfo*)obj1;
            ApplyForClassInfo* rhs = (ApplyForClassInfo*)obj2;
            
            if ([lhs.weekDay integerValue] == [rhs.weekDay integerValue])
            {
                if ([lhs.courseNumber integerValue] < [rhs.courseNumber integerValue])
                {
                    return NSOrderedAscending;
                }
                else if ([lhs.courseNumber integerValue] > [rhs.courseNumber integerValue])
                {
                    return NSOrderedDescending;
                }
            }
            
            if ([lhs.weekDay integerValue] < [rhs.weekDay integerValue])
            {
                return NSOrderedAscending;
            }
            else if ([lhs.weekDay integerValue] > [rhs.weekDay integerValue])
            {
               return NSOrderedDescending;
            }
            return NSOrderedSame;
        }
        
        return NSOrderedSame;
    }];
}

//排序
- (NSMutableArray*)sortArrDataSource:(NSMutableArray*)sourceDataArr
{
    //Step1:获取字符串中文字的拼音首字母并与字符串共同存放
    NSMutableArray *chineseStringsArray=[NSMutableArray array];
    NSMutableDictionary *chineseStringsDic=[NSMutableDictionary dictionary];
    for (int i=0; i<[sourceDataArr count]; i++)
    {
        ChineseString *chineseString=[[ChineseString alloc] init];
        AppForClaTeaInfo* appInfo = [sourceDataArr objectAtIndex:i];
        chineseString.string=[NSString stringWithString:appInfo.userName];
        chineseString.saveInfo = appInfo.userCode;
        if(chineseString.string==nil)
        {
            chineseString.string=@"";
        }
        
        if (![chineseString.string isEqualToString:@""])
        {
            NSString *pinYinResult=[NSString string];
            for (int j=0; j<chineseString.string.length; j++)
            {
                NSString *singlePinyinLetter=[[NSString stringWithFormat:@"%c",pinyinFirstLetter([chineseString.string characterAtIndex:j])]uppercaseString];
                
                pinYinResult=[pinYinResult stringByAppendingString:singlePinyinLetter];
            }
            chineseString.pinYin=pinYinResult;
        }
        else
        {
            chineseString.pinYin=@"";
        }
        [chineseStringsArray addObject:chineseString];
        
        if (0 < chineseString.saveInfo.length)
        {
            [chineseStringsDic setObject:appInfo forKey:chineseString.saveInfo];
        }
    }
    
    //Step3:按照拼音首字母对这些Strings进行排序
    NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"pinYin" ascending:YES]];
    [chineseStringsArray sortUsingDescriptors:sortDescriptors];
    
    // Step4:如果有需要，再把排序好的内容从ChineseString类中提取出来
    NSMutableArray *result=[NSMutableArray array];
    for (int i=0; i<[chineseStringsArray count]; i++)
    {
        NSString* chineseStr = ((ChineseString*)[chineseStringsArray objectAtIndex:i]).saveInfo;
        if (chineseStr && (0 < chineseStr.length))
        {
            [result addObject:[chineseStringsDic objectForKey:chineseStr]];
        }
        //[result addObject:((ChineseString*)[chineseStringsArray objectAtIndex:i]).string];
    }
    
    return result;
}

- (NSMutableArray*)parseStuCourseInfo:(NSArray*)arr
{
    NSMutableArray* courseArray = [[NSMutableArray alloc] init];
    for (unsigned int i = 0; i < arr.count; i++)
    {
        ApplyForClassInfo* classInfo = [[ApplyForClassInfo alloc] init];
        NSDictionary* dic = [arr objectAtIndex:i];
        dic = [dic processDictionaryIsNSNull:dic];
        
        classInfo.courseCode = [dic objectForKey:@"courseCode"];
        classInfo.courseName = [dic objectForKey:@"courseName"];
        classInfo.courseNumber = [dic objectForKey:@"courseNumber"];
        classInfo.pkUserCourseId = [dic objectForKey:@"pkUserCourseId"];
        classInfo.termName = [dic objectForKey:@"termName"];
        classInfo.weekDay = [dic objectForKey:@"weekDay"];
        classInfo.couseId = [dic objectForKey:@"courseId"];
        
        [courseArray addObject:classInfo];
    }
    
    return courseArray;
}

- (void)initView
{
    //init tableView
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-49-15);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.scrollEnabled = YES;
    [_tableView registerClass:[ApplyClassTableViewCell class]
       forCellReuseIdentifier:NSStringFromClass([ApplyClassTableViewCell class])];
    [self.view addSubview:_tableView];
    
    if (!_bCallName)
    {
        UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0,
                                                                  ApplyClassCellHeight*_appClassArr.count,
                                                                  CGRectGetWidth(self.view.bounds), 100)];
        footer.backgroundColor = [UIColor clearColor];
        
        UIButton* saveBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        saveBtn.frame = CGRectMake(50, 50,[UIScreen mainScreen].bounds.size.width-50*2,50);
        [saveBtn setTitle:@"下一步" forState:UIControlStateNormal];
        saveBtn.layer.cornerRadius = 4.5;
        [saveBtn addTarget:self action:@selector(nextBtn) forControlEvents:UIControlEventTouchUpInside];
        [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        saveBtn.backgroundColor = RGB(252, 120, 61);
        saveBtn.enabled = YES;
        [footer addSubview:saveBtn];
        _tableView.tableFooterView = footer;
    }
}

//上下午点击事件响应
- (void)moraftBtn:(id)sender
{
    UIButton* btn = (UIButton*)sender;
    if (100 == btn.tag)
    {
        _bottomLineView.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/8,
                                           ApplyClassCellHeight-1,
                                           [UIScreen mainScreen].bounds.size.width/4,
                                           1);
    }
    
    if (200 == btn.tag)
    {
        _bottomLineView.frame = CGRectMake([UIScreen mainScreen].bounds.size.width*5/8,
                                           ApplyClassCellHeight-1,
                                           [UIScreen mainScreen].bounds.size.width/4,
                                           1);
    }
}

//下一步点击事件响应
- (void)nextBtn
{
    /***************************************** mod 0923
    NSArray* arr = (NSArray*)_appselectArr;
    arr = [self sortArray:arr];
    NSString* sCourseNum = @"";
    for (unsigned int i = 0; i < arr.count; i++)
    {
        ApplyForClassInfo* cancleInfo = [arr objectAtIndex:i];
        if (0 == i)
        {
            sCourseNum = [NSString stringWithFormat:@"%@",cancleInfo.courseNumber];
        }
        else
        {
            sCourseNum = [NSString stringWithFormat:@"%@,%@",sCourseNum,cancleInfo.courseNumber];
        }
    }
    
    if (0 == sCourseNum.length)
    {
        [SVProgressHUD showErrorWithStatus:@"请选择课时"];
        return;
    }
    **************************************/
    
    AppForClaLeaUpLoadPhoViewController* appForClassViewCtrl = [[AppForClaLeaUpLoadPhoViewController alloc] init];
    //appForClassViewCtrl.strCourseNum = sCourseNum;
    appForClassViewCtrl.bIsOutLeave = NO;
    appForClassViewCtrl.strDate = _sDate;
    appForClassViewCtrl.teacherID = _appForTeaInfo.userCode;
    appForClassViewCtrl.courseName = _courseNameTxtView.text;
    appForClassViewCtrl.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:appForClassViewCtrl animated:YES];
}

- (UIView*)topView
{
    UIViewController *recentView = self;
    
    while (recentView.parentViewController != nil)
    {
        recentView = recentView.parentViewController;
    }
    return recentView.view;
}

//删除背景视图
- (void)removeBackView
{
    if (_backgroundView)
    {
        [_backgroundView removeFromSuperview];
        _backgroundView = nil;
    }
}

#pragma mark - ASDatePickerViewDelegate
- (void)datePickerCancel
{
    [self removeBackView];
}

- (void)dataPickSelect:(NSInteger)selectTag selectDate:(NSString*)selectData
{
    NSDate* date = [self convertDateFromString:selectData];
    self.strNavTitle = [self getYearMonthDay:date];
    
    _sDate = [self.strNavTitle stringByReplacingOccurrencesOfString:@"." withString:@"-"];
    //[self getTeaCourseInfo:_appForTeaInfo.userCode];
    //[self getStuCourseInfo:_sDate];
    
    [self removeBackView];
}

- (NSDate*)convertDateFromString:(NSString*)uiDate
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *date = [dateFormatter dateFromString:uiDate];
    NSLog(@"%@", date);
    
    return date;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_appClassArr count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ApplyClassTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ApplyClassTableViewCell class])];
    
    ApplyForClassInfo* cancleInfo = [_appClassArr objectAtIndex:indexPath.row];
    
    NSString *week = @"";
    if (cancleInfo.weekDay && (0 < cancleInfo.weekDay.length))
    {
         week = [_weekDic objectForKey:cancleInfo.weekDay];
    }
    
    NSString *day = [self getday:cancleInfo.courseNumber];
    //cell.classRowLab.text = [NSString stringWithFormat:@"%@%@(%@)", week, day,cancleInfo.courseNumber];
    cell.classRowLab.text = [NSString stringWithFormat:@"%@%@", week, day];
    cell.classRowLab.frame = CGRectMake(12, 10, 100, 25);
    cell.classContentLab.frame = CGRectMake(120, 10, [UIScreen mainScreen].bounds.size.width-120-25-20, 25);
//    cell.classTimeLab.text = [NSString stringWithFormat:@"%@",cancleInfo.classTime];
    cell.classContentLab.text = [NSString stringWithFormat:@"%@",cancleInfo.courseName];
    cell.claSeleImage.hidden = !cancleInfo.isSelect;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (NSString*)getday:(NSString*)sCourseNumber
{
    if (!sCourseNumber ||(0 == sCourseNumber.length))
    {
        return @"";
    }
    
    long courseNumber = [sCourseNumber integerValue];
    
    if ((0 < courseNumber) && (5 > courseNumber))
    {
        return @"上午";
    }
    
    if ((4 < courseNumber) && (9 > courseNumber))
    {
        return @"下午";
    }
    
    if ((8 < courseNumber) && (13 > courseNumber))
    {
        return @"晚上";
    }
    
    return @"";
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ApplyClassCellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ApplyForClassInfo* cancleInfo = [_appClassArr objectAtIndex:indexPath.row];
    cancleInfo.isSelect = !cancleInfo.isSelect;
    
    if (_bCallName)
    {
        for (int i=0; i<_appselectArr.count; i++)
        {
            ApplyForClassInfo* selectInfo = [_appselectArr objectAtIndex:i];
            if (selectInfo.isSelect)
            {
                selectInfo.isSelect = NO;
            }
        }
        
        if (0 < _appselectArr.count)
        {
            [_appselectArr removeAllObjects];
        }
    }
    
    if (cancleInfo.isSelect)
    {
        if (![_appselectArr containsObject:cancleInfo])
        {
            [_appselectArr addObject:cancleInfo];
        }
    }
    else
    {
        if ([_appselectArr containsObject:cancleInfo])
        {
            [_appselectArr removeObject:cancleInfo];
        }
    }
    if (_bCallName)
    {
        if (_delegate && [_delegate respondsToSelector:@selector(getAppForClaCourseInfo:)])
        {
            [_delegate getAppForClaCourseInfo:cancleInfo];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else
    {
        [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField;
{
    [textField resignFirstResponder];
    
    return YES;
}

@end



